<template>
    <div class="container-box">
      <el-dialog title="表格列显示" :visible.sync="dialogVisible" :show-close="true" :close-on-click-modal="false" width="60%" top="5vh" @close="dialogVisible = false" custom-class="customDialog">
        <el-form class="demo-form-inline" :inline="true" :model="query">
        <!-- <el-form ref="dialogForm" class="form-box" :inline="true" :model="dialogForm" :rules="rules" label-width="120px" title="商品"> -->
          <el-table :data="list" :border="true" :max-height="tableHeight">
            <template v-for="(item, index) in dialogColumns">
              <el-table-column :key="index" :prop="item.key" :label="item.title">
                <template slot-scope="scope">
                  <div class="table_column_div">
                    <el-input-number v-if="item.type === 'number'" v-model="scope.row[item.key]" :controls="false" />
                    <el-switch v-else-if="item.type === 'boolean'" v-model="scope.row[item.key]" />
                    <el-input v-else v-model="scope.row[item.key]" :placeholder="`请输入${item.label}`" />
                  </div>
                  <!-- <div class="" v-else>{{handleRowResult(item, scope.row)}}</div> -->
                </template>
              </el-table-column>
            </template>
            <!-- <el-table-column label="操作">
              <template slot-scope="{row, $index}">
                <el-button type="primary" @click="handleRowOption({row, index: $index,}, 'batch')">批量录入</el-button>
              </template>
            </el-table-column> -->
          </el-table>
            <!-- <el-form-item :key="index" :label="colmun.title">
              <el-input v-model="query[column.key]" :placeholder="`请输入${column.title}`" :clearable="column.clearable" @change="handleList(column.key, $event)" />
            </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { goodsIndex
    // , goodsAdd, updateAttrConfig
  } from '../../api/goods';
  import { customerAdd, customerDetail } from '../../api/customer';
  import curde from '@/mixins/curde'
  
  export default {
    name: 'ColumnForm',
    mixins: [curde],
    data() {
      return {
        dialogColumns: [
          { title: '表头名称', key: 'title', type: 'text' },
          // { title: '排序', key: 'sort', type: 'text' },
          { title: '表格是否显示', key: 'isTable', type: 'boolean' },
        ],
        list: [],
        saving: false,
        dialogVisible: false,
        rules: {
          company_name: [
            { required: true, message: '请输入单位名称', trigger: ['change', 'blur'] }
            // { required: true, message: '分类名称已存在', validator: cateNameValidator }
          ],
          full_goods_name: [
            { required: true, message: '请输入商品名称-简称', trigger: ['change', 'blur'] }
            // { required: true, message: '分类名称已存在', validator: cateNameValidator }
          ],
          customer_name: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
          area: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
          company_type: [{ required: true, message: '请选择企业类型', trigger: ['change', 'blur'] }]
        },
        // dialogForm: {
        //   area: '广东省 广州市',
        //   area_address: '天健广场',
        //   bank: '123123',
        //   bank_name: '中国银行',
        //   company_name: '单位全称',
        //   full_company_name: '单位简称',
        //   company_type: '1',
        //   customer_name: '林',
        //   customer_type: '1',
        //   phone: '13812312312',
        //   remarks: '备注',
        //   status: '1',
        //   tel_phone: '020123123'
        // },
        dialogForm: {
          area: '',
          area_address: '',
          bank: '',
          bank_name: '',
          company_name: '',
          full_company_name: '',
          company_type: '',
          customer_name: '',
          customer_type: '1',
          phone: '',
          remarks: '',
          status: '1',
          tel_phone: ''
        },
        id: '',
        operateType: '',
        goodsSelects: [],
        expandKeys: []
      };
    },
    computed: {
      storeHouseDict() {
        return this.$store.getters.storeHouseDict;
      },
      tableHeight() {
        const winHeight = window.innerHeight;
        console.log('tableHeight==', winHeight);
        const dialogHeader = document.getElementsByClassName('el-dialog__header')?.offsetHeight || 0;
        const dialogFooter = document.getElementsByClassName('el-dialog__footer')?.offsetHeight || 0;
        console.log('tableHeight--dialogHeader==', dialogHeader);
        const height = winHeight * 0.6 - dialogHeader - dialogFooter;
        console.log('tableHeight--height==', height);

        return height;
      }
    },
    watch: {
      id(val) {
        if (val) {
          this.getDetail(val);
        }
      }
    },
    created() {
      this.getData();
    },
    methods: {
      expandChange(row, expand) {
        console.log('expandChange==', row, expand, this.expandKeys);
        if (!row) return;
        if (expand) {
          this.expandKeys.push(row.id+'_0');
        } else {
          const index = this.expandKeys.findIndex(d => d === row.id+'_0');
          if (index >= 0) {
            this.expandKeys.splice(index, 1)
          }
        }
        console.log('expandChange--this.expandKeys==', this.expandKeys);
      },
      // table row 样式
      handleRowClass({row, rowIndex}) {
        if (!row) {
          return '';
        }
        if (row.sku) {
          return 'goods_item_row';
        }
      },
      handleRowClass2({row, rowIndex}) {
        if (rowIndex === 0) {
          return 'goods_item_row';
        }
        else {
          const preRow = this.list[rowIndex - 1];
          if (preRow.id !== row.id) {
            return 'goods_item_row';
          }
          return '';
        }
      },
      rowDblclick(row, column, event) {
        console.log('rowDblclick==', row);
        if (!parseInt(row.sku_id)) {
          this.$message.warning('请选择具体的规格商品');
          return;
        }
        this.$emit('callback', 'rowDblclick', row);
      },
      // 显示弹框
      showDialog(columns) {
        this.$set(this, 'list', columns);
        this.dialogVisible = true;
      },
      // 关闭弹框
      closeDialog() {
        this.dialogVisible = false;
      },
      // 获取商品数据
      async getData() {
        const { data } = await goodsIndex();
        this.allList = data?.list || [];
        this.goodsSelects = [];  // 储存商品名称 过滤使用
        this.list = data.list.map(d => {
          this.goodsSelects.push({ label: d.goods_name, value: d.id });
          d.sku_id = '0';
          d.stock = 0;
          if (d.attrValue && d.attrValue.length) {
            d.attrValue = d.attrValue.map(t => {
              let attrItem = { ...d, ...t, sku_id: t.id };
              delete attrItem.attrValue;  // 移除多余字段
              const attrStock = t.attrStock || [];
              if (attrStock.length) {
                attrStock.forEach(s => {
                  if (s.sku_id) {
                    d.stock += s.stock;
                  }
                })
              }
              attrItem.stock = 0;  // 此处的 stock 是d.stock 需移除，防止以为是商品库存
              return attrItem;
            })
          }
          return d;
        });
      },
      // 把商品数据中的规格展开；attrConfig
      handleSpreadList() {
        const allList = this.$json.cloneDeep(this.allList);
        let spreadList = [];
        const socketData = {};
        const goodsSelects = [];  // 存储商品名称
        console.log('allList==', allList);
        allList.forEach(d => {
          // 收集商品名称；
          goodsSelects.push({ label: d.goods_name, value: d.id });
  
          const attrValue = d.attrValue || [];
  
          if (attrValue.length > 0) {
            const goodsItem = attrValue.map(attr => {
              const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
              return this.$json.cloneDeep(attrItem);
            })
            spreadList = spreadList.concat(goodsItem);
          }
          else {
            spreadList.push({ ...d, attrConfigValue: null });
          }
        })
        console.log('spreadList==', spreadList);
        this.spreadList = spreadList;
        this.goodsSelects = goodsSelects;
        this.socketData = socketData;
        this.handleList();
      },
      // 把商品数据中的规格展开；
      handleSpreadList2() {
        const allList = this.$json.cloneDeep(this.allList);
        let spreadList = [];
        const socketData = {};
        const goodsSelects = [];
        allList.forEach(d => {
          // 收集商品名称；
          goodsSelects.push({ label: d.goods_name, value: d.id });
  
          // 判断商品单规格 ｜ 多规格
          let attrConfig = [];
          if (d?.attrConfig?.config) {
            attrConfig = JSON.parse(d?.attrConfig?.config || '[]')
          }
          // 多规格
          if (attrConfig.length > 0) {
            const goodsItem = attrConfig.map(attr => {
              // socketData[`${d.id}_${attr.sku}`] = attr
              const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
              return this.$json.cloneDeep(attrItem);
            })
            spreadList = spreadList.concat(goodsItem);
          }
          else {
            spreadList.push({ ...d, attrConfigValue: null });
          }
        })
        this.spreadList = spreadList;
        this.goodsSelects = goodsSelects;
        this.socketData = socketData;
        this.handleList();
      },
      // 展示符合条件的数据
      handleList() {
        this.list = this.filterData(this.spreadList, this.createPayload(this.query));
        console.log('goodsDialog--this.list==', this.list);
        this.paging.total = this.list.length;
      },
  
      async getDetail(id) {
        const res = await customerDetail({ id: id || this.id });
        console.log('customerDetail--res==', res);
      },
      // dialog 提交；
      onDialogConfirm() {
        console.log('onDialogConfirm--this.list==', this.list);
        this.$emit('callback', this.list);
        // let isValid = false;
        // console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
        // this.$refs.dialogForm.validate(valid => {
        //   console.log('onDialogConfirm--valid==', valid);
        //   isValid = valid;
        // })
        // console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
        // if (this.saving) return this.$message.error('请勿重复提交');
        // if (!isValid) return;
        // this.saving = true;
        // this.saving = false;
      },
      // 处理table 单元格显示；
      handleRowResult(item, row) {
        console.log('handleRowResult--item', item, row);
        const value = row[item.key] || '';
        if (item.key === 'goods_name' || item.key === 'full_goods_name') {
          // const sku = row.attrConfigValue && row.attrConfigValue.sku ? row.attrConfigValue.sku : '';
          return `<strong>${value} ${row?.sku || ''}</strong>`;
        }
        if (item.key === 'stock') { // 库存
          
          const attrStock = row.attrStock || [];
          if (attrStock.length > 0) {
            const skus = attrStock;
            return skus.map(d => {
              let skuValue = '';
              if (!d.sku_id) {
                return '0';
              }
              if (d.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
                const unitNum = d.stock % row.unit_convert2;
                const unitNum2 = Math.floor(d.stock / row.unit_convert2);
                if (unitNum2) {
                  skuValue = `${unitNum2}${row.unit_name2}`;
                }
                if (unitNum) {
                  skuValue = skuValue + `${unitNum}${row.unit_name}`;
                }
                // skuValue = `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
              }
              else {
                skuValue = `${d.stock}${row.unit_name}`
              }
              let storeName = d.store_house_id ? this.storeHouseDict[d.store_house_id].store_house_name : '';
              // if (storeName && storeName.indexOf('-')) {
              //   const indexOf = storeName.indexOf('-');
              //   indexOf < storeName.length-1 && (storeName = storeName.slice(indexOf+1))
              // }
              return (`${storeName}: ${skuValue}`)
              // return (`${this.storeHouseDict[d.store_house_id].store_house_name}: ${skuValue}`)
            }).join('\n')
          }
          return '';
          // const socketKey = `${d.id}_${attr.store_house_id}_${attr.sku}`
          // if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          //   const unitNum = row.stock % row.unit_convert2;
          //   const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          //   // return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
          //   let skuValue = '';
          //   if (unitNum2) {
          //     skuValue = `${unitNum2}${row.unit_name2}`;
          //   }
          //   if (unitNum) {
          //     skuValue = skuValue + `${unitNum}${row.unit_name}`;
          //   }
          //   return skuValue;
          // }
          // return `${row.stock}${row.unit_name}`
        }
        // if (item.key === 'cat_id') {
        //   const category = this.goodsCategoryDict[value]
        //   return category?.cat_name || value
        // }
        if (item.key === 'unit_name') {
          return `${row.unit_name} / ${row.unit_name2 || '-'}`
        }
        if (item.key === 'unit_convert') {
          if (row.unit_name2) {
            return `${row.unit_convert2}${row.unit_name} = ${row.unit_convert}${row.unit_name2}`
          }
          return
        }
        return value;
      }
    }
  }
  
</script>
<style lang="scss" scoped>
  .container-box {
    padding: 20px;
    ::v-deep .el-dialog.customDialog {
      //弹出层里内容的高度
      .el-table {
        height: 100%;
        overflow: scroll;
        ::v-deep .cell {
          white-space: pre-line !important;
          display: flex;
        }
        ::v-deep .goods_item_row {
          background-color: #fdf5e6;
        }
        .el-pagination {
          margin-top: 10px;
          text-align: right;
        }
      }  
    }
    ::v-deep .el-dialog__body{
      height: 60vh;
      padding-top: 0;
      padding-bottom: 0;
    }
  }
</style>
  